package com.ctgu.rabbitmq.rabbitmq.delayQueue.deadLetterDelayQueue;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ ClassName DeadLetterDelayQueue
 * @ Author Alex2
 * @ Date 2025/8/15 15:02
 **/
@Configuration
public class DeadLetterDelayQueueConfig {
    // 普通交换机
    public static final String NORMAL_EXCHANGE_DELAY_QUEUE = "normal_exchange_delay_queue";
    public static final String NORMAL_DELAY_QUEUE = "normal_delay_queue";
    public static final String NORMAL_ROUTING_KEY_DELAY_QUEUE = "normal_routing_key_delay_queue";

    // 死信交换机
    public static final String DLX_EXCHANGE_DELAY_QUEUE = "dlx_exchange_delay_queue";
    public static final String DLX_DELAY_QUEUE = "dlx_delay_queue";
    public static final String DLX_ROUTING_KEY_DELAY_QUEUE = "dlx_routing_key_delay_queue";


    // 普通交换机
    @Bean
    public DirectExchange normalExchangeDelayQueue() {
        return new DirectExchange(NORMAL_EXCHANGE_DELAY_QUEUE);
    }

    // 死信交换机
    @Bean
    public DirectExchange dlxExchangeDelayQueue() {
        return new DirectExchange(DLX_EXCHANGE_DELAY_QUEUE);
    }

    // 普通队列（绑定死信交换机）
    @Bean
    public Queue normalDelayQueue() {
        return QueueBuilder.durable(NORMAL_DELAY_QUEUE)
                .withArgument("x-dead-letter-exchange", DLX_EXCHANGE_DELAY_QUEUE)
                .withArgument("x-dead-letter-routing-key", DLX_ROUTING_KEY_DELAY_QUEUE)
                .withArgument("x-message-ttl", 10 * 60 * 1000) // 消息10分钟过期
                .build();
    }

    // 死信队列
    @Bean
    public Queue dlxDelayQueue() {
        return QueueBuilder.durable(DLX_DELAY_QUEUE).build();
    }

    // 绑定普通队列到普通交换机
    @Bean
    public Binding normalBindingDelayQueue() {
        return BindingBuilder.bind(normalDelayQueue()).to(normalExchangeDelayQueue()).with(NORMAL_ROUTING_KEY_DELAY_QUEUE);
    }

    // 绑定死信队列到死信交换机
    @Bean
    public Binding dlxBindingDelayQueue() {
        return BindingBuilder.bind(dlxDelayQueue()).to(dlxExchangeDelayQueue()).with(DLX_ROUTING_KEY_DELAY_QUEUE);
    }
}